<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AForm ref="formRef" :model="form" auto-label-width>
        <ARow :gutter="10">
          <ACol :span="12">
            <AFormItem
              :field="(attrs.title as string).includes('新增') ? 'productID' : 'materialName'"
              label="原材料名称"
              :rules="[{ required: true, message: '请选择原材料' }]"
              :validate-trigger="['change', 'input', 'blur']"
            >
              <ASelect
                v-if="(attrs.title as string).includes('新增')"
                v-model="form.productID"
                v-model:input-value="productSearch"
                allow-search
                placeholder="请选择原材料名称"
                :trigger-props="{ contentStyle: { width: 'max-content' } }"
                :filter-option="proFilter"
                @change="changeEvent('product')"
              >
                <template #empty>
                  <div style="padding: 6px 12px">
                    <ALink :hoverable="false" @click="openAdd()"> 新增原材料 </ALink>
                  </div>
                </template>
                <AOption
                  v-for="(item, index) in productList"
                  :key="index"
                  :label="item.productName"
                  :value="`${item.productId}-${item.specModel}`"
                  :disabled="`${item.productId}-${item.specModel}` === form.productID"
                >
                  <div class="w100 erp-row-center-between">
                    <div>{{ item.productName }}</div>
                    <ATag v-if="item.specModel" color="blue">
                      {{ item.specModel }}
                    </ATag>
                  </div>
                </AOption>
              </ASelect>
              <AInput v-else v-model="form.materialName" placeholder="请输入产品名称" />
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="materialCategory" label="类别">
              <AInput v-model="form.materialCategory" placeholder="请输入类别" />
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="spec" label="规格">
              <AInput v-model="form.spec" placeholder="请输入规格" />
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="materialCode" label="材质代码">
              <AInput v-model="form.materialCode" placeholder="请输入材质代码" />
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="materialDesc" label="材质">
              <AInput v-model="form.materialDesc" placeholder="请输入材质" />
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="fluteType" label="楞型">
              <AInput v-model="form.fluteType" placeholder="请输入楞型" />
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="boxSpec" label="成箱规格">
              <AInput v-model="form.boxSpec" placeholder="请输入成箱规格" />
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="crimpLine" label="压线">
              <AInput v-model="form.crimpLine" placeholder="请输入压线" />
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="unit" label="单位">
              <AInput v-model="form.unit" placeholder="请输入单位" />
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem
              field="stockQty"
              label="库存数量"
              :rules="[{ required: true, message: '请输入库存数量' }]"
              :validate-trigger="['change', 'input', 'blur']"
            >
              <!-- <AInputNumber
                v-if="(attrs.title as string).includes('新增')"
                v-model="form.stockQty"
                model-event="input"
                placeholder="请输入库存数量"
                hide-button
                :precision="0"
                :step="1"
              /> -->
              <div>{{ form.stockQty }}</div>
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="stockWarningQty" label="预警值">
              <AInputNumber
                v-model="form.stockWarningQty"
                model-event="input"
                placeholder="预警值"
                hide-button
                :step="1"
              />
            </AFormItem>
          </ACol>
        </ARow>
      </AForm>
    </AModal>
    <addProduct
      v-model:visible="addProductVisible"
      title="新增原材料"
      :check-data="{ productName: productSearch }"
      @reload="getProductList"
    ></addProduct>
  </div>
</template>

<script lang="ts" setup>
import { Message, SelectOptionData } from '@arco-design/web-vue'
import { getProductAllList, ProductResItem } from '@renderer/api/salesDep'
import { editStock, StockReq, StockResItem } from '@renderer/api/warehouseManage'
import { useMenuState } from '@renderer/store'
import { deleteNullObject } from '@renderer/utils/data-processing'
import addProduct from '@renderer/views/Information/MaterialInfo/editPopupForm.vue'

interface Props {
  [key: string]: any
  checkData?: Partial<StockResItem>
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return {}
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const form = ref<StockReq>({
  supplierId: '',
  materialName: '',
  materialCategory: '',
  spec: '',
  materialCode: '',
  materialDesc: '',
  fluteType: '',
  boxSpec: '',
  crimpLine: '',
  unit: '',
  storageArea: '',
  materialType: 0,
  stockQty: 0,
  unitPrice: 0,
  remark: '',
  materialStockId: '',
  amount: 0
})
const menuParam = useMenuState()
const productList = ref<ProductResItem[]>([])
const addProductVisible = ref(false)
const productSearch = ref('')

const getProductList = async () => {
  const res = await getProductAllList({ productType: 1 })
  productList.value = res.data.list
}

// 弹窗事件
const modalEvent = async (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors: any) => {
        if (!errors) {
          // 新增
          if ((attrs.title as string).includes('新增')) {
            form.value.materialStockId = undefined
            const temp = productList.value.find(
              (item) => `${item.productId}-${item.specModel}` === form.value.productID
            )
            form.value.materialName = temp!.productName!
            form.value.productID = undefined
          }
          form.value.materialType = 0
          editStock(deleteNullObject(form.value)).then(() => {
            Message.success((attrs.title as string).includes('新增') ? '新增成功' : '修改成功')
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value = {
        supplierId: '',
        materialName: '',
        materialCategory: '',
        spec: '',
        materialCode: '',
        materialDesc: '',
        fluteType: '',
        boxSpec: '',
        crimpLine: '',
        unit: '',
        storageArea: '',
        materialType: 0,
        stockQty: 0,
        unitPrice: 0,
        remark: '',
        materialStockId: '',
        amount: 0
      }
      emit('update:visible', false)
      break
    case 'open':
      {
        menuParam.switchEditStatus(true)
        await getProductList()
        Object.assign(form.value, props.checkData)
        const temp = productList.value.find(
          (item) =>
            item.productName === props.checkData.materialName &&
            item.specModel === props.checkData.spec
        )
        if (temp) {
          form.value.productID = `${temp.productId}-${temp.specModel}`
        }
      }
      break
    case 'cancel':
      formRef.value.resetFields()
      form.value = {
        supplierId: '',
        materialName: '',
        materialCategory: '',
        spec: '',
        materialCode: '',
        materialDesc: '',
        fluteType: '',
        boxSpec: '',
        crimpLine: '',
        unit: '',
        storageArea: '',
        materialType: 0,
        stockQty: 0,
        unitPrice: 0,
        remark: '',
        materialStockId: '',
        amount: 0
      }
      menuParam.switchEditStatus(false)
      emit('update:visible', false)
      break

    default:
      break
  }
}

// 新增原材料
const openAdd = () => {
  addProductVisible.value = true
}

const changeEvent = (type: string) => {
  switch (type) {
    case 'product':
      {
        const temp = productList.value.find(
          (item) => `${item.productId}-${item.specModel}` === form.value.productID
        )
        if (temp) {
          form.value.spec = temp.specModel!
          form.value.unit = temp.unit!
          form.value.materialCategory = temp.productCategory!
          form.value.materialCode = temp.materialCode!
          form.value.fluteType = temp.fluteType!
          form.value.materialDesc = temp.materialDesc!
          form.value.crimpLine = temp.crimpLine!
        }
      }
      break

    default:
      break
  }
}

const proFilter = (inputValue: string, option: SelectOptionData) => {
  return (
    (option.value as string)?.split('-')[1].includes(inputValue) ||
    option.label!.includes(inputValue)
  )
}
</script>
<style scoped>
:deep(.arco-select-option-content) {
  width: 100%;
}
</style>
